package com.woniuxy.consumer;

import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.woniuxy.entity.DTO.GoodsItemDTO;
import com.woniuxy.entity.ShoppingCarts;
import com.woniuxy.mapper.ShoppingCartsMapper;
import com.woniuxy.util.RabbitMQConst;
import com.woniuxy.util.SnowflakeIdGenerator;
import com.woniuxy.util.UserContext;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class AddShoppingCartConsumer {
    @Resource
    private ShoppingCartsMapper shoppingCartsMapper;
    @RabbitListener(queues = RabbitMQConst.ADD_SHOPPING_CART_QUEUE)
    public void addShoppingCartConsumer(String msg, Channel channel, Message message){

        try {

            List<ShoppingCarts> products = JSON.parseArray(msg, ShoppingCarts.class);
            List<ShoppingCarts> shoppingCarts = new ArrayList();
           for (ShoppingCarts shoppingCart : products){
               ShoppingCarts shoppingCarts1 = new ShoppingCarts();
               shoppingCarts1.setUserId(shoppingCart.getUserId());
               shoppingCarts1.setProductId(shoppingCart.getProductId());
               shoppingCarts1.setQuantity(shoppingCart.getQuantity());
               shoppingCarts.add(shoppingCarts1);
           }
            shoppingCartsMapper.addShoppingCart(shoppingCarts);



            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException ex) {
                e.printStackTrace();
            }
        }

    }
    @RabbitListener(queues = RabbitMQConst.ADD_SHOPPING_CART_BY_PRODUCT_ID_QUEUE)
    public void addShoppingCartByProductIdConsumer(String msg, Channel channel, Message message){
        try {
            ShoppingCarts shoppingCarts = JSON.parseObject(msg, ShoppingCarts.class);

            shoppingCartsMapper.addShoppingCartByProductId(shoppingCarts);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
        catch (Exception e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException ex) {
                e.printStackTrace();
            }
        }
    }
}
